/***
 * @Author: 玄绮 shijiahansi@qq.com
 * @Date: 2024-06-06 13:54:07
 * @LastEditors: 玄绮 shijiahansi@qq.com
 * @LastEditTime: 2024-06-06 13:54:10
 * @FilePath: \client\src\tools\http\UpLoadFile.cpp
 * @Description:
 * @
 * @Copyright (c) 2024 by 玄绮, All Rights Reserved.
 */
#include "UpLoadFile.h"

#include <QFile>
#include <QHttpMultiPart>
#include <QHttpPart>
#include <QJsonObject>
#include <QJsonValue>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <qfileinfo.h>
#include <qjsondocument.h>
#include <qnetworkrequest.h>

QNetworkAccessManager UpLoadFile::manager;

UpLoadFile::UpLoadFile(QObject* parent) : QObject(parent) {
}

UpLoadFile::~UpLoadFile() {
}

void UpLoadFile::put(QString filename) {
    QUrl            url("http://127.0.0.1:4091/uploadfile");
    QNetworkRequest request(url);

    auto config = request.sslConfiguration();
    config.setPeerVerifyMode(QSslSocket::VerifyNone);
    config.setProtocol(QSsl::TlsV1SslV3);
    request.setSslConfiguration(config);

    QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    QHttpPart imagePart;
    imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
    QFile*    file = new QFile(filename);
    QFileInfo info(filename);
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; filename=" + info.fileName()));
    file->open(QIODevice::ReadOnly);
    imagePart.setBodyDevice(file);
    file->setParent(multiPart);  // 现在不能删除文件，所以用 multiPart 删除

    multiPart->append(imagePart);

    // manager.post()
    QNetworkReply* reply = manager.post(request, multiPart);
    multiPart->setParent(reply);  // 用 reply 删除 multiPart
    // 这里连接信号等

    connect(reply, &QNetworkReply::finished, this, &UpLoadFile::on_finished);
    connect(reply, &QNetworkReply::readyRead, this, &UpLoadFile::on_readyRead);
    connect(reply, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error),
        [=](QNetworkReply::NetworkError code) {
            QNetworkReply* reply = static_cast<QNetworkReply*>(sender());

            /*这里可以通过 code 知道哪里错了*/
            // std::cout << "error:" <<
            qDebug() << "error: " << code;
            reply->deleteLater();
        });
}

void UpLoadFile::on_readyRead() {
    QNetworkReply* reply = static_cast<QNetworkReply*>(sender());

    auto    data = reply->readAll();
    QString s(data);
    qDebug() << "on_readyRead:" << s;

    auto jsonDoc = QJsonDocument::fromJson(data);

    // 获取 JSON 对象
    QJsonObject jsonObj = jsonDoc.object();

    // 获取 "status" 对象
    QJsonObject statusObj = jsonObj.value("status").toObject();

    // 获取 "code" 和 "message" 字段
    int     code    = statusObj.value("code").toInt();
    QString message = statusObj.value("message").toString();

    QString url = "";
    if (code == 0) {
        // 获取 "url" 字段
        url = jsonObj.value("url").toString();
    }

    emit finished(url);

    reply->deleteLater();
}

void UpLoadFile::on_finished() {
    QNetworkReply* reply = static_cast<QNetworkReply*>(sender());
    auto           list  = reply->rawHeaderList();

    qDebug() << "url:" << reply->url();
    if (reply->header(QNetworkRequest::ContentLengthHeader) == 0) {
        reply->deleteLater();
        emit finished("");
    }
}
